<template>
  <div>
    <!-- <div v-if="!comments.length">
      <p>No comment yet, leave a comment</p>
    </div>-->
    <div>
      <Feedback :isSuccess="isSuccess" :isError="isError" :text="text"></Feedback>
    </div>
    <report-card :open-dialog="dialog" v-on:closeDialog="dialog = false" :info="selectedComment"
      :type="2"></report-card>
    <div v-for="(comment, i) in loading ? 4 : comments" :key="comment.commentId">
      <v-skeleton-loader type="list-item-avatar-two-line" :loading="loading">
        <v-card class="transparent" flat>
          <v-list-item three-line class="pl-0 mt-2">
            <v-list-item-avatar v-if="typeof comment.senderId !== 'undefined'" size="50">
              <v-img v-if="comment.avatar !== 'no-photo.jpg'" class="elevation-6" :src="comment.avatar"></v-img>
              <v-avatar v-else color="red">
                <span class="white--text headline">
                  {{ comment.nickName.split("")[0].toUpperCase() }}
                </span>
              </v-avatar>
            </v-list-item-avatar>
            <v-list-item-content>
              <div class="d-flex mb-0">
                <v-list-item-title v-if="comment.senderId" class="font-weight-medium caption mb-0 d-flex">
                  {{ comment.nickName }}
                  <span class="pl-2 font-weight-light grey--text">
                    {{ dateFormatter(comment.createTime) }}
                  </span>
                </v-list-item-title>
                <v-menu bottom left>
                  <template v-slot:activator="{ on }">
                    <v-btn icon v-on="on">
                      <v-icon>mdi-dots-vertical</v-icon>
                    </v-btn>
                  </template>

                  <v-list v-if="isAuthenticated">
                    <v-list-item @click="deleteComment(comment.commentId)">
                      <v-list-item-title>
                        <v-icon>mdi-trash</v-icon>删除
                      </v-list-item-title>
                    </v-list-item>
                    <v-list-item @click="report(comment)">
                      <v-list-item-title>
                        <v-icon>mdi-trash</v-icon>举报
                      </v-list-item-title>
                    </v-list-item>
                  </v-list>
                </v-menu>
              </div>
              <v-list-item-subtitle class="mt-n2 black--text text--darken-4 caption">{{ comment.content
                }}</v-list-item-subtitle>

              <div>
                <v-btn text small :ripple="false" @click.stop="showMore(comment.commentId)">展开更多回复</v-btn>
                <v-btn text small :ripple="false" @click.stop="showReply(`${'reply' + comment.commentId}`)">回复</v-btn>
              </div>
              <div class="d-none" :ref="`${'reply' + comment.commentId}`">
                <v-list-item three-line class="pl-0">
                  <v-list-item-avatar v-if="typeof comment.userId !== 'undefined'" class="mt-2" size="40">
                    <v-avatar v-if="!isAuthenticated" color="primary">
                      <v-icon class="white--text">mdi-account</v-icon>
                    </v-avatar>
                    <template v-else>
                      <v-img v-if="currentUser.avatar !== 'no-photo.jpg'" class="elevation-6"
                        :src="currentUser.avatar"></v-img>
                      <v-avatar v-else color="red">
                        <span class="white--text headline">{{
                          currentUser.nickName.split("")[0].toUpperCase()
                        }}</span>
                      </v-avatar>
                    </template>
                  </v-list-item-avatar>
                  <v-list-item-content class="align-self-auto mt-0 pt-0">
                    <v-form :ref="`form${comment.commentId}`">
                      <v-text-field :ref="`${'input' + comment.commentId}`" class="pt-0 mt-0 body-2"
                        placeholder="发表一下你的看法吧..." @click="clickTextField"
                        :value="repliesInput[`input${comment.commentId}`]"></v-text-field>
                    </v-form>
                    <div :ref="comment.commentId + 'btns'" class="d-inline-block text-right" v-if="isAuthenticated">
                      <v-btn text @click="hideReply(comment.commentId)" small>取消</v-btn>
                      <v-btn class="blue darken-3 white--text" depressed tile small :loading="btnLoading && i == index"
                        @click="
                          index = i;
                        addReply($event, comment.commentId);
                        ">回复</v-btn>
                    </div>
                  </v-list-item-content>
                </v-list-item>
                <!-- </v-list-item-action> -->
              </div>
              <v-expansion-panels>
                <v-expansion-panel class="transparent elevation-0">
                  <v-expansion-panel-header v-if="comment.replies && comment.replies.length > 0"
                    class="blue--text text--darken-4 py-0">{{ comment.replies.length }} 回复</v-expansion-panel-header>
                  <v-expansion-panel-content>
                    <v-list-item three-line class="pl-0 mt-2" v-for="reply in comment.replies" :key="reply.commentId">
                      <v-list-item-avatar v-if="typeof reply !== 'undefined'" size="50">
                        <v-img v-if="reply.avatar !== 'no-photo.jpg'" class="elevation-6" :src="reply.avatar"></v-img>
                        <v-avatar v-else color="red">
                          <span class="white--text headline">{{
                            reply.nickName.split("")[0].toUpperCase()
                          }}</span>
                        </v-avatar>
                      </v-list-item-avatar>
                      <v-list-item-content>
                        <div class="d-flex mb-0">
                          <v-list-item-title v-if="reply.senderId" class="font-weight-medium caption mb-0 d-flex">
                            {{ reply.nickName }}
                            <span class="pl-2 font-weight-light grey--text">
                              {{ dateFormatter(reply.createTime) }}
                            </span>
                          </v-list-item-title>
                          <v-menu bottom left v-if="isAuthenticated">
                            <template v-slot:activator="{ on }">
                              <v-btn icon v-on="on">
                                <v-icon>mdi-dots-vertical</v-icon>
                              </v-btn>
                            </template>

                            <v-list>
                              <v-list-item @click="
                                deleteReply(
                                  comment.commentId,
                                  reply.commentId
                                )
                                ">
                                <v-list-item-title>
                                  <v-icon>mdi-trash</v-icon>删除
                                </v-list-item-title>
                              </v-list-item>
                              <v-list-item @click="report(comment)">
                                <v-list-item-title>
                                  <v-icon>mdi-trash</v-icon>举报
                                </v-list-item-title>
                              </v-list-item>
                            </v-list>
                          </v-menu>
                        </div>
                        <v-list-item-subtitle class="mt-n2 black--text text--darken-4 caption">{{ reply.content
                          }}</v-list-item-subtitle>
                      </v-list-item-content>
                    </v-list-item>
                  </v-expansion-panel-content>
                </v-expansion-panel>
              </v-expansion-panels>
            </v-list-item-content>
          </v-list-item>
        </v-card>
      </v-skeleton-loader>
    </div>
    <div>
      <v-btn text small :ripple="false" @click.stop="getComments()">展开更多评论</v-btn>
    </div>
  </div>
</template>

<script>
import moment from "moment";
import { mapGetters } from "vuex";
import {
  deleteCommentById,
  getComments,
  postComment,
} from "../../services/CommentRequest";
import ReportCard from "@/components/ReportCard";
import Feedback from "../Feedback.vue";
export default {
  props: {
    videoId: {
      type: Number,
      required: true,
    },
  },
  data: function () {
    return {
      dialog: false,
      selectedComment: null,
      isSuccess: false,
      isError: false,
      text: "",
      firstPageIndex: 1,
      replyMap: {},
      repliesInput: {},
      comments: this.$store.getters.getComments.data,
      commentsLength: false,
      index: -1,
      btnLoading: false,
      snackbar: false,
      loading: false,
      replies: [],
    };
  },
  computed: {
    ...mapGetters(["isAuthenticated", "currentUser"]),
  },
  watch: {
    isError() {
      if (this.isError) {
        setTimeout(() => {
          this.isError = false
        }, 3000)
      }
    },
    isSuccess(){
      if (this.isSuccess) {
        setTimeout(() => {
          this.isSuccess = false
        }, 3000)
      }
    }
  },
  methods: {
    report(comment) {
      this.selectedComment = comment
      this.dialog = true
    },
    async addReply(event, id) {
      this.replyMap[id] = 1;
      let comment = this.comments.find(
        (comment) => comment.commentId.toString() === id.toString()
      );
      // comment.replies = comment.replies.filter((reply)=> reply.commentId.toString()===replyId.toString())
      comment.replies = [];
      if (!this.isAuthenticated) return;
      if (this.$refs[`input${id}`][0].$refs.input.value == "") return;
      this.btnLoading = true;
      // console.log((event.target.loading = true))
      this.$refs[`form${id}`][0].reset();
      // console.log(this.$refs[`input${id}`][0].$refs.input.value)
      console.log(this.$refs[`input${id}`][0].$refs.input.value);
      const reply = await postComment({
        videoId: this.videoId,
        calledId: id,
        content: this.$refs[`input${id}`][0].$refs.input.value,
      })
        .catch((err) => {
          console.log(err);
        })
        .finally(() => {
          this.btnLoading = false;
          // this.$store.dispatch('setComments', this.videoId)
        });
      if (!reply) return;
      this.hideReply(id);
      // this.$store.dispatch('addComment', reply.data.data)
      // console.log(this.$store.getters.getComments.data)
      this.text = "回复成功";
      this.isSuccess = true;
      this.$emit("addCommentCount");
    },
    async getComments() {
      this.loading = true;
      if (this.firstPageIndex == 1) {
        const comments = await this.$store
          .dispatch("setComments", {
            videoId: this.videoId,
            pageSize: 5,
            pageIndex: this.firstPageIndex,
          })
          .catch((err) => console.log(err))
          .finally(() => (this.loading = false));

        // console.log(this.loading)
        if (!comments) return;
        this.firstPageIndex++;
        this.comments = this.$store.getters.getComments;
        console.log(this.comments);
      } else {
        const comments = await getComments({
          videoId: this.videoId,
          pageSize: 5,
          pageIndex: this.firstPageIndex,
        });
        if (!comments) return;
        if (comments.data.data.list.length == 0) {
          console.log("无数据");
          this.loading = false;
          return;
        }
        this.comments = this.comments.concat(comments.data.data.list);
        this.firstPageIndex++;
        console.log(this.comments);
      }
      this.loading = false;
    },
    async deleteComment(id) {
      if (!this.isAuthenticated) return;
      // this.$store.dispatch('deleteComment', id)

      // await CommentService.deleteById(id).catch((err) => {
      //   console.log(err)
      // })
      deleteCommentById(id)
      .then(res=>{
        this.text = res.data.message
        if(res.data.code==200){
          this.isSuccess = true
        }else{
          this.isError = true 
        }
      })
      // await this.$store
      //   .dispatch('setComments', { videoId: this.videoId, pageSize: 5, pageIndex: 1 })
      //   .catch((err) => console.log(err))
      // this.comments = this.$store.getters.getComments.data
      this.$emit("videoCommentLength");
    },
    async showMore(id) {
      console.log("获取回复");
      if (!this.replyMap[id]) {
        this.replyMap[id] = 1;
      }
      const replies = await getComments({
        calledId: id,
        pageSize: 5,
        pageIndex: this.replyMap[id],
      });
      // console.log(this.loading)
      if (!replies) return;
      this.replyMap[id]++;
      let comment = this.comments.find(
        (comment) => comment.commentId.toString() === id.toString()
      );
      console.log(comment);
      if (!comment.replies) {
        // console.log('1')
        comment.replies = [];
        comment.replies = comment.replies.concat(replies.data.data.list);
      } else {
        // console.log('2')
        comment.replies = comment.replies.concat(replies.data.data.list);
        // this.comments
        //   .find((comment) => comment._id === id)
        //   .replies.unshift(reply.data.data)
      }
      const cache = this.comments;
      this.comments = [];
      this.comments = cache;
      console.log(comment.replies);
    },
    async deleteReply(commentId, replyId) {
      this.deleteComment(replyId);
      let comment = this.comments.find(
        (comment) => comment.commentId.toString() === commentId.toString()
      );
      // comment.replies = comment.replies.filter((reply)=> reply.commentId.toString()===replyId.toString())
      this.replyMap[commentId] = 1;
      comment.replies = [];
    },
    clickTextField() {
      if (!this.isAuthenticated) return this.$router.push("/signin");
    },
    showReply(id) {
      this.$refs[id][0].classList.toggle("d-none");
    },
    hideReply(id) {
      this.$refs[`form${id}`][0].reset();
      this.$refs["reply" + id][0].classList.toggle("d-none");
    },
    dateFormatter(date) {
      return moment(date)
        .locale("zh-cn")
        .fromNow();
    },
  },
  components: {
    ReportCard,
    Feedback
  },
  mounted() {
    this.comments = [];
    this.getComments();
    // console.log(this.comments)
  },
};
</script>

<style lang="scss">
.v-application--is-ltr .v-expansion-panel-header__icon {
  margin-left: initial;
}

.v-expansion-panel::before {
  box-shadow: initial;
}

.custom-alert {
  color: #68c23c;
  /* 深绿色文字 */
}

.custom-alert-error {
  color: #f56c6c;
}
</style>
